import { SearchOutlined } from '@ant-design/icons'
import { Button, Input, Space } from 'antd'
import { useState } from 'react'

export default function useTableSearch() {
  const [search, setSearch] = useState({})

  const handleSearch = ({ dataIndex, selectedKeys, close, confirm }) => {
    setSearch((prev) => ({ ...prev, [dataIndex]: selectedKeys[0] }))
    confirm() // 控制 filterIcon
    close()
  }
  const handleSearchReset = ({ dataIndex, clearFilters, close, confirm }) => {
    clearFilters()
    setSearch((prev) => ({ ...prev, [dataIndex]: '' }))
    confirm() // 控制 filterIcon
    close()
  }
  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input.Search
          placeholder={`Search`}
          allowClear
          enterButton="查询"
          onClear={() => handleSearchReset({ dataIndex, clearFilters, close, confirm })}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch({ dataIndex, selectedKeys, close, confirm })}
          onSearch={() => handleSearch({ dataIndex, selectedKeys, close, confirm })}
          style={{ marginBottom: 8, width: 188 }}
        />
        <Space>
          <Button
            onClick={() => handleSearchReset({ dataIndex, clearFilters, close, confirm })}
            style={{ marginLeft: 4 }}>
            清空
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (isConfirm) => {
      return <SearchOutlined style={{ color: isConfirm ? '#1677ff' : undefined }} />
    },
  })
  return { search, getColumnSearchProps, onClear: setSearch }
}
